package com.whmall.service.crm.module.supplierdeveloppool.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whmall.component.entity.dto.PageReqDTO;
import com.whmall.component.entity.dto.PageRspDTO;
import com.whmall.component.enumeration.CompanyTypeEnum;
import com.whmall.component.enumeration.OperatorTypeEnum;
import com.whmall.service.crm.entity.dto.supplierdevelop.*;
import com.whmall.service.crm.enumeration.SupplierControlDirectoryEnum;
import com.whmall.service.crm.enumeration.SupplierDevelopPoolOperationTypeEnum;
import com.whmall.service.crm.enumeration.SupplierDevelopStatusEnum;
import com.whmall.service.crm.exception.AcquireSupplierExceedExceptiom;
import com.whmall.service.crm.module.company.dao.CompanyInformationMapper;
import com.whmall.service.crm.module.company.dao.CompanyMapper;
import com.whmall.service.crm.module.company.entity.CompanyDO;
import com.whmall.service.crm.module.company.entity.CompanyInformationDO;
import com.whmall.service.crm.module.company.entity.qo.CompanyQO;
import com.whmall.service.crm.module.company.service.CompanyIndustryTypeService;
import com.whmall.service.crm.module.companyuser.dao.CompanyUserMapper;
import com.whmall.service.crm.module.companyuser.entity.CompanyUserDO;
import com.whmall.service.crm.module.companyuser.entity.qo.CompanyUserQO;
import com.whmall.service.crm.module.supplierdeveloppool.service.SupplierDevelopPoolLogService;
import com.whmall.service.crm.module.supplierdeveloppool.service.SupplierDevelopPoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SupplierDevelopPoolServiceImpl implements SupplierDevelopPoolService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private CompanyInformationMapper companyInformationMapper;

    @Autowired
    private SupplierDevelopPoolLogService poolLogService;

    /**
     * 供应商最大开发次数
     */
    public static final int MAX_DEVELOP_TIMES = 50;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private CompanyIndustryTypeService companyIndustryTypeService;

    /**
     * 上架产品数量大于300 需要修改供应商控制目录
     */
    public static final int SUPPLIER_PRODUCT_NUMS = 300;


    @Override
    public PageRspDTO<SupplierDevelopQueryRspDTO> list(PageReqDTO pageReqDTO, SupplierDevelopQueryRepDTO repDTO) {

        CompanyQO qo = new CompanyQO();
        if (repDTO != null && repDTO.getIsControlDirectory() != null && repDTO.getIsControlDirectory() == 1) {
            List<Integer> controlDirectories = Arrays.asList(SupplierControlDirectoryEnum.BRAND_REAGENT.getValue(),
                    SupplierControlDirectoryEnum.SALES_LOCK_ACCOUNT_COMPANY.getValue(),
                    SupplierControlDirectoryEnum.SHELF_PRODUCT_GREATER_300.getValue(),
                    SupplierControlDirectoryEnum.SIGNED_COOPERATION_SUPPLIER.getValue(),
                    SupplierControlDirectoryEnum.OTHER_SITUATION.getValue());
            qo.setSupplierControlDirectorys(controlDirectories);
        } else if (repDTO != null && repDTO.getIsControlDirectory() != null && repDTO.getIsControlDirectory() == 0) {
            qo.setSupplierControlDirectorys(Arrays.asList(0));
        }
        // 设置条件
        qo.setIsSupplier(1);
        qo.setIsLogout(0);
        if (repDTO != null && repDTO.getCompanyId() != null) {
            qo.setIds(Arrays.asList(repDTO.getCompanyId()));
        }
        qo.setSupplierDevelopStatus(repDTO.getSupplierDevelopStatus());
        qo.setVmId(repDTO.getVmId());
        qo.setOrderBy(" id desc ");
        // 查询结果
        PageInfo<CompanyDO> pageInfo = PageHelper.startPage(pageReqDTO.getPageNum(),
                pageReqDTO.getPageSize()).doSelectPageInfo(() -> companyMapper.listBy(qo));
        if (CollUtil.isEmpty(pageInfo.getList())) {
            return new PageRspDTO<>(pageInfo.getPageNum(), pageInfo.getPageSize(),
                    pageInfo.getPages(), (int) pageInfo.getTotal(), new ArrayList<SupplierDevelopQueryRspDTO>());
        }
        List<Long> companyIds = pageInfo.getList().stream().
                map(e -> e.getId()).collect(Collectors.toList());
        // 关联info表相关信息
        Map<Long, CompanyInformationDO> companyInfos = companyInformationMapper.getByIds(companyIds)
                .stream().collect(Collectors.toMap(CompanyInformationDO::getId, e -> e));
        List<SupplierDevelopQueryRspDTO> developQueryRspDTOS = pageInfo.getList().stream().map(companyDO -> {
            SupplierDevelopQueryRspDTO developQueryRspDTO = new SupplierDevelopQueryRspDTO();
            BeanUtils.copyProperties(companyDO, developQueryRspDTO);
            if (companyInfos.containsKey(companyDO.getId())) {
                developQueryRspDTO.setSupplierDevelopTimes(
                        companyInfos.get(companyDO.getId()).getSupplierDevelopTimes());
                developQueryRspDTO.setSupplierShelfProduct(
                        companyInfos.get(companyDO.getId()).getSupplierShelfProduct());
            }
            return developQueryRspDTO;
        }).collect(Collectors.toList());
        return new PageRspDTO<>(pageInfo.getPageNum(), pageInfo.getPageSize(),
                pageInfo.getPages(), (int) pageInfo.getTotal(), developQueryRspDTOS);
    }

    @Override
    @Transactional
    public void acquireSupplier(Long employeeId, Long companyId) {

        Assert.notNull(companyId, "公司id不能为空");
        Assert.notNull(employeeId, "操作人id不能为空");

        int inDevelopCount = companyMapper.getInDevelopCount(companyId);
        if (inDevelopCount >= MAX_DEVELOP_TIMES) {
            throw new AcquireSupplierExceedExceptiom("获取失败！抱歉您名下开发中的供应商总数已达上限数50家");
        }
        CompanyDO companyDO = companyMapper.selectById(companyId);
        if (!companyDO.getSupplierDevelopStatus().
                equals(SupplierDevelopStatusEnum.TO_BE_DEVELOPMENT.getValue())) {
            throw new IllegalArgumentException("只有待开发状态的供应商才能获取");
        }

        companyDO.setSupplierDevelopStatus(SupplierDevelopStatusEnum.IN_DEVELOPMENT.getValue());
        companyDO.setVmId(employeeId);
        companyDO.setUpdateId(employeeId);
        companyDO.setUpdateTime(new Date());

        // 修改供应商开发状态
        companyMapper.updateById(companyDO);
        // 添加 供应商开发次数
        companyInformationMapper.increaseDevelopTimes(companyId);
        // 添加日志
        poolLogService.addLog(SupplierDevelopPoolLogSaveReqDTO.builder()
                .companyId(companyId)
                .handleId(employeeId)
                .operationType(SupplierDevelopPoolOperationTypeEnum.GET_SUPPLIER.getValue())
                .handleType(OperatorTypeEnum.EMPLOYEE.getValue())
                .build());
    }

    @Override
    @Transactional
    public void releaseSupplier(ReleaseSupplierReqDTO reqDTO) {

        Assert.notNull(reqDTO.getCompanyId(), "公司id不能为空");
        Assert.notNull(reqDTO.getEmployeeId(), "操作人id不能为空");
        if (StrUtil.isEmpty(reqDTO.getRemark())) {
            throw new IllegalArgumentException("释放原因不能为空");
        }

        CompanyDO companyDO = companyMapper.selectById(reqDTO.getCompanyId());
        companyDO.setSupplierDevelopStatus(SupplierDevelopStatusEnum.TO_BE_DEVELOPMENT.getValue());
        companyDO.setUpdateId(reqDTO.getEmployeeId());
        companyDO.setUpdateTime(new Date());
        /*if (!companyDO.getSupplierDevelopStatus().
                equals(SupplierDevelopStatusEnum.TO_BE_DEVELOPMENT.getValue())){
            throw new IllegalArgumentException("只有待开发状态的供应商才能获取");
        }*/
        // 修改供应商开发状态
        companyMapper.updateById(companyDO);
        // 添加日志
        poolLogService.addLog(SupplierDevelopPoolLogSaveReqDTO.builder()
                .companyId(reqDTO.getCompanyId())
                .handleId(reqDTO.getEmployeeId())
                .operationType(SupplierDevelopPoolOperationTypeEnum.RELEASE_SUPPLIER.getValue())
                .handleType(OperatorTypeEnum.EMPLOYEE.getValue())
                .build());
    }

    @Override
    @Transactional
    public void addControlDirectory(AddControlDirectoryReqDTO reqDTO) {

        Assert.notNull(reqDTO.getCompanyId(), "公司id不能为空");
        Assert.notNull(reqDTO.getEmployeeId(), "操作人id不能为空");
        Assert.notNull(reqDTO.getSupplierControlDirectory(), "添加原因不能为空");

        CompanyDO companyDO = companyMapper.selectById(reqDTO.getCompanyId());
        if (!companyDO.getSupplierControlDirectory().equals(
                SupplierControlDirectoryEnum.NO_CONTROL_DIRECTORY.getValue())) {
            return;
        }
        // 添加控制目录 时  开发状态修改为 不需开发
        companyDO.setSupplierDevelopStatus(SupplierDevelopStatusEnum.NO_DEVELOPMENT_REQUIRED.getValue());
        companyDO.setSupplierControlDirectory(reqDTO.getSupplierControlDirectory());
        companyDO.setUpdateId(reqDTO.getEmployeeId());
        companyDO.setUpdateTime(new Date());
        /*if (!companyDO.getSupplierDevelopStatus().
                equals(SupplierDevelopStatusEnum.TO_BE_DEVELOPMENT.getValue())){
            throw new IllegalArgumentException("只有待开发状态的供应商才能获取");
        }*/
        // 修改供应商控制目录
        companyMapper.updateById(companyDO);
        // 添加日志
        poolLogService.addLog(SupplierDevelopPoolLogSaveReqDTO.builder()
                .companyId(reqDTO.getCompanyId())
                .handleId(reqDTO.getEmployeeId())
                .operationType(SupplierDevelopPoolOperationTypeEnum.ADD_CONTROL_DIRECTORY.getValue())
                .handleType(OperatorTypeEnum.EMPLOYEE.getValue())
                .build());
    }

    @Override
    @Transactional
    public boolean removeControlDirectory(Long employeeId, Long companyId) {
        Assert.notNull(companyId, "公司id不能为空");
        Assert.notNull(employeeId, "操作人id不能为空");

        CompanyDO companyDO = companyMapper.selectById(companyId);
        // 移除控制目录 时  开发状态修改为 待开发
        companyDO.setSupplierDevelopStatus(SupplierDevelopStatusEnum.TO_BE_DEVELOPMENT.getValue());
        companyDO.setSupplierControlDirectory(SupplierControlDirectoryEnum.NO_CONTROL_DIRECTORY.getValue());
        companyDO.setUpdateId(employeeId);
        companyDO.setUpdateTime(new Date());

        if (!canRemoveControlDirectory(companyId)) {
            return false;
        }
        // 修改供应商控制目录
        companyMapper.updateById(companyDO);
        // 添加日志
        poolLogService.addLog(SupplierDevelopPoolLogSaveReqDTO.builder()
                .companyId(companyId)
                .handleId(employeeId)
                .operationType(SupplierDevelopPoolOperationTypeEnum.REMOVE_CONTROL_DIRECTORY.getValue())
                .handleType(OperatorTypeEnum.EMPLOYEE.getValue())
                .build());
        return true;
    }

    /**
     * 是否能移除控制目录
     *
     * @param companyId
     * @return
     */
    @Override
    @Transactional
    public boolean canRemoveControlDirectory(Long companyId) {

        CompanyInformationDO companyInformationDO = companyInformationMapper.getById(companyId);
        if (companyInformationDO.getSupplierShelfProduct() >= SUPPLIER_PRODUCT_NUMS) {
            return false;
        }
        CompanyDO companyDO = companyMapper.selectById(companyId);

        Map<Long, String> companyIndustryTypeMap = companyIndustryTypeService.getTypeStrByCompanyIds(Collections.singletonList(companyDO.getId()));

        if (companyIndustryTypeMap.getOrDefault(companyDO.getId(), "").contains(String.valueOf(
                CompanyTypeEnum.REAGENT.getValue()))) {
            return false;
        }
        List<CompanyUserDO> companyUserDOS = companyUserMapper.listBy(
                CompanyUserQO.builder().companyId(companyId)
                        .isLockedSale(true).isLogout(false).build());
        if (CollUtil.isNotEmpty(companyUserDOS)) {
            return false;
        }
        return true;
    }


}
